package cn.learn.validate;

import cn.learn.properties.SecurityProperties;
import cn.learn.validate.image.ImageValidateCodeGenerator;
import cn.learn.validate.sms.DefaultSmsCodeSender;
import cn.learn.validate.sms.SmsCodeSender;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * 创建验证码的bean的管理类
 *
 * @author huangyezhan
 * @date 2020年2月18日21:49:51
 */
@Configuration
public class ValidateCodeBeanConfig {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private Producer       producer;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 如果有名字叫做imageValidateCodeGenerator的bean,则不在创建了；@ConditionalOnMissingBean(name = "imageValidateCodeGenerator")
     *
     * @return 返回图形验证码的生成器对象
     */
    @Bean
    @ConditionalOnMissingBean(ImageValidateCodeGenerator.class)
    public ImageValidateCodeGenerator imageValidateCodeGenerator() {
        ImageValidateCodeGenerator graph = new ImageValidateCodeGenerator();
        graph.setSecurityProperties(securityProperties);
        graph.setProducer(producer);
        graph.setDefaultKaptcha(defaultKaptcha);
        return graph;
    }

    /**
     * Spring Boot的自动配置机制依靠@ConditionalOnMissingBean注解判断是否执行初始化代码，
     * 即如果用户已经创建了bean，则相关的初始化代码不再执行
     *
     * @return 返回默认的手机发送对象
     */
    @Bean
    @ConditionalOnMissingBean(SmsCodeSender.class)
    public SmsCodeSender smsCodeSender() {
        return new DefaultSmsCodeSender();
    }

}
